/**
 *
 * @description 剑指 Offer II 053. 二叉搜索树中的中序后继
 * @author 定岳
 */

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @return {TreeNode}
 */
var inorderSuccessor = function (root, p) {
  const left = (node, max) => {
    if (!node) {
      return null || max;
    }
    return left(node.left, node);
  };
  const dfs = (node, min, max) => {
    if (!node) {
      return null;
    }
    // 二叉搜索树 搜索P节点
    if (node.val === p.val) {
      return left(node.right, max);
    } else if (node.val > p.val) {
      return dfs(node.left, min, node);
    } else if (node.val < p.val) {
      return dfs(node.right, node, max);
    }
  };
  return dfs(root);
};
